package com.wu.creditmanager;

import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;

import com.wu.creditmanager.db.CreditsDbAdapter;
import com.wu.creditmanager.entity.Bill;
import com.wu.creditmanager.entity.Credit;
import com.wu.creditmanager.util.Constants;
import com.wu.creditmanager.util.TimeUtil;

public class BillService extends Service implements Runnable {

	private static final String TAG = BillService.class.getSimpleName();
	private static final long UPDATE_INTERVAL = 24 * 60 * 60 * 1000;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		new Thread(this).start();
		Log.i(TAG, "Bill Service Start");
	}

	public static void generateBills(Context context) {
		CreditsDbAdapter dbAdapter = new CreditsDbAdapter(context);
		dbAdapter.open(true);
		Time time = TimeUtil.getCurrentTime();
		List<Credit> credits = dbAdapter.findNoBillCredits(time
				.format(Constants.BILL_MONTH_FORMAT));
		Log.d(TAG, "Fetch all credits sucess,size:" + credits.size());
		for (Credit credit : credits) {
			Bill bill = Bill.generateBill(credit, time);
			dbAdapter.addBill(bill);
		}
		dbAdapter.close();
		AlarmListWidget.update(context);
	}

	public void run() {
		generateBills(this);
		Intent updateIntent = new Intent(this, BillService.class);
		PendingIntent pending = PendingIntent.getService(this, 0, updateIntent,
				0);
		long nowMillis = System.currentTimeMillis();
		long updateTime = nowMillis + UPDATE_INTERVAL;
		AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		alarm.set(AlarmManager.RTC_WAKEUP, updateTime, pending);
		Time time = new Time();
		time.set(updateTime);
		Log.i(TAG, "BillService will run at " + time.format("%m-%d %H:%M:%S"));
		stopSelf();
	}

	public static void updateBill(Context context, Credit credit) {
		CreditsDbAdapter dbAdapter = new CreditsDbAdapter(context);
		dbAdapter.open(true);
		Time time = TimeUtil.getCurrentTime();
		Bill newBill = Bill.generateBill(credit, time);
		Bill bill = dbAdapter.findBill(credit.getId(), newBill.getBillMonth());
		if (bill != null) {
			bill.setPaymentDueDay(newBill.getPaymentDueDay());
			bill.setStatementDay(newBill.getStatementDay());
			dbAdapter.updateBill(bill);
		}
		dbAdapter.close();
		AlarmListWidget.update(context);
	}

	public static void deleteBills(Context context, Credit credit) {
		CreditsDbAdapter dbAdapter = new CreditsDbAdapter(context);
		dbAdapter.open(true);
		dbAdapter.deleteBillByCreditId(credit.getId());
		dbAdapter.close();
		AlarmListWidget.update(context);
	}

}
